package com.als.healthymananger.controller.impl;

import com.als.healthymananger.controller.JurisdictionGroupApi;
import com.als.healthymananger.dto.JurisdictionDto;
import com.als.healthymananger.entity.Jurisdiction;
import com.als.healthymananger.entity.JurisdictionGroup;
import com.als.healthymananger.service.JurisdictionGroupService;
import com.als.healthymananger.service.JurisdictionsService;
import com.als.healthymananger.utils.RespBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/system/jurisdiction")
public class JurisdictionGroupController implements JurisdictionGroupApi {
    @Autowired
    private JurisdictionGroupService jurisdictionGroupService;
    @Autowired
    private JurisdictionsService jurisdictionsService;

    @Override
    public RespBean createJurisdictionGroups(String userType, int jurisdictionId) {
        return jurisdictionGroupService.save(new JurisdictionGroup(userType, jurisdictionId))? RespBean.ok("添加成功"): RespBean.badRequest("添加失败");
    }

    @Override
    public RespBean deleteJurisdictionGroups(String userType, int jurisdictionId) {
        return jurisdictionGroupService.remove(new QueryWrapper<JurisdictionGroup>().eq("type_name", userType).eq("jurisdiction_id", jurisdictionId))? RespBean.ok("删除成功"): RespBean.badRequest("删除失败");
    }

    @Override
    public RespBean getUserType(String userType) {
        List<JurisdictionGroup> list = jurisdictionGroupService.list(new QueryWrapper<JurisdictionGroup>().eq("type_name", userType));
        if (list == null) {
            return RespBean.ok("获取成功");
        }

        List<String> jurisdictionIds = list.stream().map(jurisdiction -> {
            Integer jurisdictionId = jurisdiction.getJurisdictionId();
            return "/system/jurisdiction/" + String.valueOf(jurisdictionId);
        }).collect(Collectors.toList());

        return RespBean.ok("获取成功", new JurisdictionDto(userType, jurisdictionIds));
    }

    @Override
    public RespBean getJurisdictions() {
        List<Jurisdiction> list = jurisdictionsService.list();
        return RespBean.ok("获取成功", list);
    }

    @Override
    public RespBean getJurisdiction(int jurisdictionId) {
        Jurisdiction jurisdiction = jurisdictionsService.getById(jurisdictionId);
        return jurisdiction == null? RespBean.badRequest("获取失败"): RespBean.ok("获取成功", jurisdiction);
    }
}
